package com.example.demo_job.config;

import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@Component
public class MySessionListener implements HttpSessionListener {

    private static Set<HttpSession> sessions = Collections.synchronizedSet(new HashSet<>());
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        sessions.add(se.getSession()); // 会话创建时添加到集合
        System.out.println("Session created: " + se.getSession().getId());

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        sessions.remove(se.getSession()); // 会话销毁时从集合中移除
        System.out.println("Session destroyed: " + se.getSession().getId());
    }



    public static void loginout(String username){
        for (HttpSession httpSession:sessions){
            String user = (String) httpSession.getAttribute("currentUser");
            if (user!= null && user.equals(username)){
                httpSession.invalidate();//销毁会话
                break;
            }
        }
    }
    public static Set<HttpSession> getSessions() {
        return sessions; // 获取当前活跃的会话
    }
}
